import { Cascader, Spin } from "antd";
import { useState, useEffect } from "react";
import { xhrPostJson } from "@/services/index";

const SelectCity = (props: any) => {
  const [loading, setLoading] = useState(true);
  const {
    countryCode = "CN",
    api,
    placeholder = "请选择",
    notFoundContent = "暂无数据",
    ...others
  } = props;
  const [value, setValue] = useState();
  const [options, setOptions] = useState([]);
  

  useEffect(async () => {
    setLoading(true);
    // 增加其他国家城市选择不适用的处理逻辑
    if (countryCode !== 'CN') {
      setOptions([{ code: 'No', name: '不适用', isLeaf: true}]);
      setLoading(false);
      return;
    }
    const data = await getData(countryCode);
    if (props.defaultValue) {
      try {
        const res: any = await xhrPostJson(api.findByCode, {
          code: props.defaultValue,
        });
        if (res.success) {
          setValue([res.result.parentId, res.result.code]);
          const childrenData = await getData(res.result.parentId);
          data.map((item: { code: any; children: any; }) => {
            if (item.code === res.result.parentId) {
              item.children = childrenData;
            }
            return item;
          });
        }
      } catch (e) {}
    }
    setOptions(data);
    setLoading(false);
  }, [countryCode]);

  const getData = async (parentId: string) => {
    try {
      const res: any = await xhrPostJson(api.url, {
        parentId: parentId,
        ...props.params
      });
      if (res.success) {
        return res.result.map((item: any) => {
          return {
            ...item,
            isLeaf: item.isLeaf == "1",
          };
        });
      } else {
        return [];
      }
    } catch (e) {
      return [];
    }
  };

  const onChange = (value: string | any[], selectedOptions:any) => {
    console.log('onChange 2', value, selectedOptions)
    if(countryCode !== 'CN') {
      props?.onChange(value, selectedOptions[0].name);
    } else if (value && value.length != 1) {
      props?.onChange(value, selectedOptions[1].name);
    }
  };
  const filter = (inputValue: string, path: any[]) =>
    path.some(
      (option) =>
        option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
    );

  return (
    <Spin spinning={loading}>
      <Cascader
        {...others}
        notFoundContent={notFoundContent}
        placeholder={placeholder}
        autoFocus
        value={value}
        options={options}
        onChange={onChange}
        fieldNames={{ label: "name", value: "code", children: "children" }}
        showSearch={{
          filter,
        }}
      />
    </Spin>
  );
};

export default SelectCity;
